import json
import base64
import lz4.block as lb
import numpy as np


class ReadJson(object):
    def __init__(self):
        pass

    def __del__(self):
        pass

    @classmethod
    def read_map_data(cls, str_data: str):
        map_list = json.loads(str_data)
        map_json = json.loads(map_list[0])
        if "data" in map_json.keys():
            return map_json["data"]
        pass

    @staticmethod
    def read_path_data(data: str):
        map_json = json.loads(data)
        if len(map_json) != 0:
            return map_json[0]
        else:
            return ""

    @classmethod
    def decompress_map_data(cls, compress_str: str, map_width: int, map_height: int):
        lz4str = base64.b64decode(compress_str)
        d_length = map_width * map_height
        map_data = lb.decompress(lz4str, uncompressed_size=d_length)
        map_array = np.frombuffer(map_data, dtype=np.uint8)
        if len(map_array) != 0:
            return map_array.reshape(map_height, map_width)
        else:
            return

    @staticmethod
    def get_map_value(data: str):
        read = ReadJson()
        map_dict = read.read_map_data(data)
        map_dict['MapArray'] = read.decompress_map_data(map_dict['map'],
                                                        map_dict['width'],
                                                        map_dict['height'])
        return map_dict

    @staticmethod
    def get_forbid_pos(region_data: str):
        read = ReadJson()
        region_dict = read.read_map_data(region_data)
        return region_dict


